////
////  GRAddDevice.m
////  Smart
////
////  Created by XJYMAC on 16/11/2.
////  Copyright © 2016年 Gree Inc. All rights reserved.
////
//
//#import "GRConfigManger.h"
//#import "LTLink.h"
//#import "AppDelegate.h"
//#import "GRAddShowSuccessDeviceViewController.h"
//#import "GRChooseDeviceViewController.h"
//
////杭州古北
//#import "NetworkAPI.h"
//@interface GRConfigManger()<GRReveicePacketDelegate>
//
//
//@property(nonatomic,strong) GRUdpSendPacket *socketSend;
//@property(nonatomic,strong) GRUdpReceivePacket *socketReveive;
///**发包数据*/
//@property(nonatomic,strong)NSData *data;
//@property(nonatomic,copy)GRConfigResultBlock configResultBlock;
//@property(nonatomic,strong)NSTimer *tenChangeTime;
//@end
//
//extern deviceType devicetype;
//@implementation GRAddDevice
//{
//    BOOL configSwitch;//高通 no 结束发包 yes 一直发包
//    NSInteger tenChangeTimeBool; //1 发江波龙  2发古北
//    LTLink  *mlink;
//    NSDictionary *_dict;
//    NSInteger macCount;
//    NSTimer *_macTime;
//    NetworkAPI *api;
//}
//
//
//
//- (instancetype)init
//{
//    if (self = [super init]) {
//        
//        _socketSend = [[GRUdpSendPacket alloc] init];
//        mlink = [[LTLink alloc] init];
//        _macArray = [NSMutableArray array];
//        api = [[NetworkAPI alloc] init];
//    }
//    return self;
//}
//
//- (void)startConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord  configTime:(CGFloat)configTime configResultBlock:(GRConfigResultBlock)configResultBlock
//{
//    
//    _socketReveive= [[GRUdpReceivePacket alloc] initWithDelegate:self];
//    [_socketReveive bindToPort:8001 error:nil];
//    [_socketReveive receiveWithTimeOut:configTime];
//    
//    NSString *configDisHost = [[NSUserDefaults standardUserDefaults] objectForKey:@"configDisHost"];
//    NSString *hostStr = configDisHost;
//    if (hostStr.length > 12) {
//        hostStr = [hostStr substringToIndex:2];
//    }else
//    {
//        hostStr = @"";//空字符串代表中国
//    }
//    
//    NSString *PASSWORD = passWord;
//    PASSWORD = [NSString stringWithFormat:@"%@+%@",PASSWORD,hostStr];
//    
//    
//    if (devicetype == deviceTypeBusinessAirContionter) {
//        
//        [self startGreeConfigWthSSID:SSID passWord:passWord configDisHost:configDisHost];
//        [self startBroadLickConfigWithSSID:SSID passWord:passWord gatewayaddr:nil];
//        
//    }else{
//        
//
//        [self startBroadLickConfigWithSSID:SSID passWord:passWord gatewayaddr:nil];
//        [NSThread sleepForTimeInterval:0.3];
//        [self pushOrStartBroadLink];//关闭古北
////
//        [self startGreeConfigWthSSID:SSID passWord:passWord configDisHost:configDisHost];
//        
//        [mlink startLinkWithSSID:SSID password:PASSWORD secureKey:nil];//开启江波龙
//        
//    
//        
////        //开启定时器
//        NSArray *SSIDPASSWOEDpasswordArray = [NSArray arrayWithObjects:SSID,PASSWORD ,nil];
//        _tenChangeTime = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(tenChangeTimeClick) userInfo:SSIDPASSWOEDpasswordArray repeats:YES];
//        tenChangeTimeBool = 1;
//    }
//    
//    
//    _configResultBlock = [configResultBlock copy];
//    
//    
//    
//}
//
//- (void)tenChangeTimeClick
//{
//    NSString *SSID = _tenChangeTime.userInfo[0];
//    NSString *PASSWORD = _tenChangeTime.userInfo[1];
//    
//    //发江波龙发
//    if (tenChangeTimeBool == 1) {
//        
//        tenChangeTimeBool = 2;
//        [self pushOrStartBroadLink];//开启古北
////        [mlink startLinkWithSSID:SSID password:PASSWORD secureKey:nil];//开启江波龙
//        
//    }else if (tenChangeTimeBool == 2){//发古北发
//        
//
//        tenChangeTimeBool = 1;
////        [mlink stopLink];//关闭江波龙
//        [self pushOrStartBroadLink];//关闭古北
//    }
//}
//
////注意  LinkWithSSID:SSID password:PASSWORD     PASSWORD 是大写 ..
//- (void)broadLickConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord gatewayaddr:(NSString *)gatewayaddr configDisHost:(NSString *)configDisHost PASSWORD :(NSString *)PASSWORD
//{
//    
//    if (_configmonitorOver) {
//        return;
//    }
//    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        [self pushOrStartBroadLink];//结束
//
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            
//            if (_configmonitorOver) {
//                return;
//            }
//            [self pushOrStartBroadLink];//开始
//
//            [self broadLickConfigWithSSID:SSID passWord:passWord gatewayaddr:gatewayaddr configDisHost:configDisHost PASSWORD:PASSWORD];
//        });
//        
//    });
//}
//
//
//
//#pragma mark -开启古北配网
//- (void)startBroadLickConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord gatewayaddr:(NSString *)gatewayaddr
//{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//        NSDictionary *dic = nil;
//        //商用空调
//        if (devicetype == deviceTypeBusinessAirContionter) {
//            
//            dic = [[NSDictionary alloc] initWithObjectsAndKeys:SSID, @"ssid", passWord, @"password",@(2),@"cfgversion",@(120),@"timeout",@(5400),@"senddelay", nil];
//            
//        }else{
//            
//             dic = [[NSDictionary alloc] initWithObjectsAndKeys:SSID, @"ssid", passWord, @"password",@(3),@"cfgversion",@(120),@"timeout",@(5400),@"senddelay", nil];//1800
//        }
//        
//        NSData *descData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
//        NSString *easyconfigResult = [api deviceEasyConfig:[[NSString alloc] initWithData:descData encoding:NSUTF8StringEncoding]];
//        
//        
//        
//        GRLog(@"easyconfigResult: %@", easyconfigResult);
//        
//        NSDictionary *dict =  [easyconfigResult JSONValue];
//        
//        [self didReceiveFromBroadLick:dict];
//        
//        GRLog(@"dict = %@",dict);
//    });
//}
//
//- (void)pushOrStartBroadLink
//{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//        [api deviceEasyConfigPauseOrRestart];
//    });
//}
//
//
//- (void)didReceiveFromBroadLick:(NSDictionary *)dict
//{
//    if ([[dict objectForKey:@"msg"] isEqualToString:@"success"]) {
//        
//        [_socketReveive stopListen];
//        NSMutableDictionary *mutabDict = [NSMutableDictionary dictionaryWithDictionary:dict];
//        mutabDict[@"t"] = @"configok";
//        mutabDict[@"r"] = @(200);
//        NSString *deviceName = [mutabDict safeObjectForKey:@"mac"];
//        deviceName = [deviceName stringByReplacingOccurrencesOfString:@":" withString:@""];
//        mutabDict[@"mac"] = deviceName;
//        mutabDict[@"devaddr"] = [mutabDict safeObjectForKey:@"devaddr"];
//        [self receiveWithDict:mutabDict];
//    }
//}
//
//
//
//
////开启格力配网
//- (void)startGreeConfigWthSSID:(NSString *)SSID passWord:(NSString *)passWord configDisHost:(NSString *)configDisHost
//{
//    configSwitch = YES;
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_async(queue, ^{
//        while (configSwitch) {
//            [self onekeyConfigWithSSID:SSID passWord:passWord configDisHost:configDisHost];
//        }
//    });
//}
//
//- (void)didReceive:(NSData *)data fromHost:(NSString *)host port:(UInt16)port
//{
//    
//    //监听一直都在,在5秒结束后设置_configmonitorOver = yes ,120秒结束监听失败,返回失败.
//    if (!_configmonitorOver) {
//        
//        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        NSDictionary *dict = [string JSONValue];
//        if (_macArray.count > 0) {
//            
//            for (NSDictionary *macDict in _macArray) {
//                
//                if ([macDict isEqualToDictionary:dict]) {
//                    
//                    return;
//                }
//            }
//        }
//        
//        if (devicetype == deviceTypeBusinessAirContionter) {
//            devicetype = deviceTypeAirContionter;
//        }
//        
//        [self receiveWithDict:dict];
//    }
//    
//}
//
//- (void)receiveWithDict:(NSDictionary *)dict
//{
//    [_macArray addSafeObject:dict];
//    
//    [self macTimeClick];
//    
//    //这里用block把通知发送出去
//    _configResultBlock(dict);
//    
//    
//    GRLog(@"_macArray= %@",_macArray);
//    
//    
////    //等待5秒钟
////    [self configWaitingSeconds:5.0];
//    
//}
//
//
//
////等待5秒钟`
//- (void)configWaitingSeconds:(double)times
//{
//    dispatch_async(dispatch_get_main_queue(), ^{
//        
//        
//        if (_macTime) {
//            
//            [_macTime invalidate];
//            _macTime = nil;
//        }
//        
//        _macTime = [NSTimer scheduledTimerWithTimeInterval:times target:self selector:@selector(macTimeClick) userInfo:nil repeats:NO];
//        
//        
//        
//    });
//}
//- (void)macTimeClick
//{
//    [_socketReveive stopListen];//5秒时间到,结束监听.
//    [mlink stopLink];
//    configSwitch = NO;
//    [api deviceEasyConfigCancel];//结束古北配网
//    _configmonitorOver = YES;
//    if (_tenChangeTime) {
//        
//        [_tenChangeTime invalidate];
//        _tenChangeTime = nil;
//    }
//    
//    
////    if ([self.delegate respondsToSelector:@selector(vc:)]) {
////        [self.delegate vc:self];
////    }
//}
//
//- (void)didNotReceiveByTimeout
//{
//    NSDictionary *dict = nil;
//    _configResultBlock(dict);
//}
//
//- (void)stopConfig
//{
//    configSwitch = NO;
//    [_socketSend close];
//    _configmonitorOver = YES;
//    [_socketReveive stopListen];
//    [api deviceEasyConfigCancel];
//    [mlink stopLink];
//    if (_macTime) {
//        
//        [_macTime invalidate];
//        _macTime = nil;
//    }
//    if (_tenChangeTime) {
//        
//        [_tenChangeTime invalidate];
//        _tenChangeTime = nil;
//    }
//}
//
//- (void)onekeyConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord configDisHost:(NSString *)configDisHost
//{
//    static NSString *str = nil;
//    NSString *hostStr = configDisHost;
//    NSString *ssid = SSID;
//    NSString *password = passWord;
//    password = [NSString stringWithFormat:@"%@+%@",password,hostStr];
//    //    NSData *data = [self jsonDataWithSSID:SSID passWord:passWord configDisHost:configDisHost];
//    NSString *dataString = @"1";//这个数字是随便填的,data数据多导致路由器缓存太多,配网速度大大下降,所以越少越好.
//    NSData *data = [dataString JSONData];
//    
//    static NSInteger  integer;
//    
//    int j = 0;
//    int k = 0;
//    for (int i = 0; i < 120; i++) {
//        
//        [NSThread sleepForTimeInterval:0.02];//0.02  50包  0.012 70包
//        integer = 0;
//        if (i == 3) {
//            integer = 120;
//        }
//        if (i <= (4 + ssid.length -1)  && i > 3 ) {
//            NSString *wifiStr =  [ssid substringWithRange:NSMakeRange(j, 1)];
//            integer = [wifiStr characterAtIndex:0];
//            
//            j++;
//            str = [NSString stringWithFormat:@"239.%d.%zd.254",i,integer];
//            [_socketSend sendData:data toHost:str port:9957];
//            
//            
//        }else if (i > 35 && i <= (36 + password.length - 1))
//        {
//            NSString *passwordStr = [password substringWithRange:NSMakeRange(k, 1)];
//            integer = [passwordStr characterAtIndex:0];
//            k++;
//            str = [NSString stringWithFormat:@"239.%d.%zd.254",i,integer];
//            [_socketSend sendData:data toHost:str port:9957];
//            
//        }else
//        {
//            str = [NSString stringWithFormat:@"239.%d.%zd.254",i,integer];
//            [_socketSend sendData:data toHost:str port:9957];
//        }
//    }
//}
//
//- (NSData *)jsonDataWithSSID:(NSString *)SSID passWord:(NSString *)passWord configDisHost:(NSString *)configDisHost
//{
//    
//    if (_data == nil) {
//        
//        NSString *hostStr = configDisHost;
//        
//        NSString *ssid = SSID;
//        NSString *password = passWord;
//        password = [NSString stringWithFormat:@"%@+%@",password,hostStr];
//        
//        
//        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:120];
//        
//        static NSInteger  integerrrr;
//        int a = 0;
//        int b = 0;
//        for (int i = 0; i < 120; i++) {
//            
//            
//            integerrrr = 0;
//            if (i == 3) {
//                integerrrr = 120;
//                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
//            }
//            else if (i <= (4 + ssid.length -1)  && i > 3 ) {
//                NSString *wifiStr =  [ssid substringWithRange:NSMakeRange(a, 1)];
//                integerrrr = [wifiStr characterAtIndex:0];
//                a++;
//                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
//                
//            }else if (i > 35 && i <= (36 + password.length - 1))
//            {
//                NSString *passwordStr = [password substringWithRange:NSMakeRange(b, 1)];
//                integerrrr = [passwordStr characterAtIndex:0];
//                
//                b++;
//                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
//            }else{
//                
//                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
//            }
//            
//        }
//        
//        NSData *data = [mutableArray JSONData];
//        return data;
//    }
//    return _data;
//}
//
//@end
